from functools import reduce
import csv
import random
import math
import operator


# 将数据导入，并划分进训练集与测试集
def load_dataset(filename, split):
    train_set = []
    test_set = []
    with open(filename, 'rt', encoding='utf-8') as csvfile:
        lines = csv.reader(csvfile)
        dataset = list(lines)
        for x in range(len(dataset) - 1):
            for y in range(4):
                dataset[x][y] = float(dataset[x][y])
            if random.random() < split:
                train_set.append(dataset[x])
            else:
                test_set.append(dataset[x])

    return train_set, test_set


# 计算欧几里得距离
def calc_distance(instance1, instance2, length):
    distance = 0
    for x in range(length):
        distance += pow((instance1[x] - instance2[x]), 2)
    return math.sqrt(distance)


# 计算最近的k个近邻
def find_neighbors(train_set, test_instance, k):
    distances = []
    length = len(test_instance) - 1
    for x in range(len(train_set)):
        dist = calc_distance(test_instance, train_set[x], length)
        distances.append((train_set[x], dist))
    distances.sort(key=operator.itemgetter(1))  # sort函数默认为升序
    neighbors = []
    for x in range(k):
        neighbors.append(distances[x][0])  # 得到k个近邻
    return neighbors


# 计算测试样例属于哪个类别
def get_response(neighbors):
    class_votes = {}  # 定义一个字典，方便计算类别个数
    for x in range(len(neighbors)):
        response = neighbors[x][-1]
        if response in class_votes:
            class_votes[response] += 1
        else:
            class_votes[response] = 1
    sorted_votes = sorted(class_votes.items(), key=operator.itemgetter(1), reverse=True)  # 降序排列
    return sorted_votes[0][0]


# 计算准确率
def calc_accuracy(test_set, predictions):
    correct = 0
    for x in range(len(test_set)):
        if test_set[x][-1] == predictions[x]:
            correct += 1
    return correct / len(test_set) * 100.0


def main():
    split = 0.67  # 设置训练集:测试集为2:1
    train_set, test_set = load_dataset('./dataset/iris/iris.data', split)  # 导入数据

    predictions = []
    k = 3  # 计算最近的3个近邻
    index_dict = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2}
    confusion_matrix = [[0 for _ in range(k)] for _ in range(k)]
    for x in range(len(test_set)):
        neighbors = find_neighbors(train_set, test_set[x], k)
        result = get_response(neighbors)
        predictions.append(result)
        confusion_matrix[index_dict.get(test_set[x][-1])][index_dict.get(result)] += 1

    # 显示混淆矩阵
    print('混淆矩阵:')
    class_list = list(index_dict.keys())
    print(reduce(lambda prev, curr: prev + f'{curr: ^15s}', class_list, ' ' * 15))
    for index, row in enumerate(confusion_matrix):
        row_str = reduce(lambda prev, curr: prev + f'{curr: ^15d}', row, f'{class_list[index]: ^15s}')
        print(row_str)
    # 计算准确度
    accuracy = calc_accuracy(test_set, predictions)
    print(f'\n准确度: {accuracy: .3f}%')


if __name__ == '__main__':
    main()
